<?php
/*
 * @Description    : APP
 * @Author         : QianLong
 * @Date           : 2023-01-11 12:13:55
 * @LastEditors    : QianLong
 * @Site           : http://21ds.cn
 * @LastEditTime   : 2024-05-15 17:39:51
 */

declare(strict_types=1);

namespace App\Controller;

use App\Common\RedisCache;
use App\Constants\Status;
use App\Exception\ApiException;
use App\Job\SignFailAddJob;
use Qianlong\Validate\Validate;

class AppController extends AbstractController
{
  public function upgrade()
  {
    $valitor = new Validate();
    $valitor->addColumn('app_id')->required();
    $valitor->addColumn('version')->required();
    $valitor->addColumn('platform')->required();
    $valitor->addColumn('time')->required();
    if ($valitor && !$this->validate($valitor)) {
      throw new ApiException(Status::CODE_BAD_REQUEST, $valitor->getError()->__toString());
    }
    unset($valitor);
    $param = $this->request->all();
    $redisCache = new RedisCache;
    $serverInfo = $redisCache->getAppInfo($param['app_id']);
    if (empty($serverInfo)) {
      throw new ApiException(Status::CODE_FAIL, 'APP不存在或已删除');
    }
    $param['version_type'] = (!isset($param['version_type']) || empty($param['version_type']))?'zhengshi': $param['version_type'];
    $newSign2 = (new \App\Service\Common)->generateSignature($param, $serverInfo['server_secret']);
    if ($param['sign'] != $newSign2['sign']) {
      return $this->response->json(Status::CODE_FAIL, 'sign签名校验失败');
    }
      $current_time = time();
      $five_minutes_ago = $current_time - (5 * 60);
      $five_minutes_later = $current_time + (5 * 60);
    if ($param['time'] < $five_minutes_ago || $param['time'] > $five_minutes_later) {
      return $this->response->json(Status::CODE_FAIL, '时间参数不合法');
    }
    $userInfo = $redisCache->getUserInfoById($serverInfo['uid']);
    if (empty($userInfo) || $userInfo['status'] != 1) {
      throw new ApiException(Status::CODE_FAIL, '用户状态异常或被禁，服务不可用，如有疑问请联系柠聚开发平台客服咨询');
    }
    if ($serverInfo['status'] != 1) {
      throw new ApiException(Status::CODE_FAIL, '当前APP状态不可用，如需使用，请登录柠聚开发平台启用后重试');
    }
    $collection = mongodb2()->selectCollection('app_version' );
    $result = $collection->findOne(['app_id' => $param['app_id'], 'status' =>1, 'upgrade_type' =>'all', 'version_type' => $param['version_type']]);
    $result = json_decode(json_encode($result), true);
    $returnResult = [];
    if (!empty($result)) {
      if ($param['platform'] == 'android' && $param['version'] < $result['version_no_android']) {
        $returnResult['platform'] = $param['platform'];
        $returnResult['upgrade_type'] = 'all';
        $returnResult['upgrade_title'] = $result['upgrade_title'];
        $returnResult['upgrade_content'] = $result['upgrade_content'];
        $returnResult['apk_url'] = $result['url_android'];
        $returnResult['store_url'] = $result['store_url_android'];
        $returnResult['force'] = $result['force'];
        $returnResult['notice_cycle'] = $result['notice_cycle'];
      } else if ($param['platform'] == 'ios' && $param['version'] < $result['version_no_ios']) {
        $returnResult['platform'] = $param['platform'];
        $returnResult['upgrade_type'] = 'all';
        $returnResult['upgrade_title'] = $result['upgrade_title'];
        $returnResult['upgrade_content'] = $result['upgrade_content'];
        $returnResult['store_id'] = $result['ios_store_id'];
        $returnResult['store_url'] = $result['url_ios'];
        $returnResult['force'] = $result['force'];
        $returnResult['notice_cycle'] = $result['notice_cycle'];
      }
      if (empty($returnResult) && isset($param['wgt_version']) && !empty($param['wgt_version'])) {
        $collection = mongodb2()->selectCollection('app_version' );
        $result = $collection->findOne(['app_id' => $param['app_id'], 'status' => 1, 'upgrade_type' =>'incr', 'version_type' => $param['version_type']]);
        $result = json_decode(json_encode($result), true);
        if (!empty($result) && $param['wgt_version'] < $result['version_incr']) {
          $returnResult['upgrade_type'] = 'incr';
          $returnResult['upgrade_title'] = $result['upgrade_title'];
          $returnResult['upgrade_content'] = $result['upgrade_content'];
          $returnResult['wgt_url'] = $result['incr_url'];
          $returnResult['force'] = $result['force'];
          $returnResult['notice_cycle'] = $result['notice_cycle'];
        }
      }
    }
    if (!empty($returnResult)) {
      $returnResult['md5'] = md5(json_encode($returnResult));
      return $this->response->json(Status::CODE_OK, 'success', $returnResult);
    }
    return $this->response->json(Status::CODE_FAIL, '当前已为最新版本', $returnResult);
  }
  public function info()
  {
    $valitor = new Validate();
    $valitor->addColumn('app_id')->required();
    $valitor->addColumn('time')->required();
    if ($valitor && !$this->validate($valitor)) {
      throw new ApiException(Status::CODE_BAD_REQUEST, $valitor->getError()->__toString());
    }
    unset($valitor);
    $param = $this->request->all();
    $redisCache = new RedisCache;
    $serverInfo = $redisCache->getAppInfo($param['app_id']);
    if (empty($serverInfo)) {
      throw new ApiException(Status::CODE_FAIL, 'APP不存在或已删除');
    }
    $newSign2 = (new \App\Service\Common)->generateSignature($param, $serverInfo['server_secret']);
    if ($param['sign'] != $newSign2['sign']) {
      $logData['url'] = $this->request->fullUrl();
      $logData['remoteIp'] = $this->dataResource->getClientIp($this->request);
      $logData['user_sign'] = $param['sign'];
      $logData['server_sign'] = $newSign2['sign'];
      $logData['server_query'] = $newSign2['query'];
      $logData['uid'] = $serverInfo['uid'];
      queue_push(new SignFailAddJob($logData));
      return $this->response->json(Status::CODE_FAIL, 'sign签名校验失败');
    }
      $current_time = time();
      $five_minutes_ago = $current_time - (5 * 60);
      $five_minutes_later = $current_time + (5 * 60);
    if ($param['time'] < $five_minutes_ago || $param['time'] > $five_minutes_later) {
      return $this->response->json(Status::CODE_FAIL, '时间参数不合法');
    }
    $userInfo = $redisCache->getUserInfoById($serverInfo['uid']);
    if (empty($userInfo) || $userInfo['status'] != 1) {
      throw new ApiException(Status::CODE_FAIL, '用户状态异常或被禁，服务不可用，如有疑问请联系柠聚开发平台客服咨询');
    }
    if ($serverInfo['status'] != 1) {
      throw new ApiException(Status::CODE_FAIL, '当前APP状态不可用，如需使用，请登录柠聚开发平台启用后重试');
    }
    $collection = mongodb2()->selectCollection('app_version' );
    $result = $collection->findOne(['app_id' => $param['app_id']]);
    $result = json_decode(json_encode($result), true);
    $returnResult = $serverInfo;
    unset($returnResult['uid'], $returnResult['username']);
    if (!empty($result)) {
      unset($result['_id'], $result['uid'], $result['username']);
      $returnResult = array_merge($returnResult,$result);
    }
    $returnResult['page_url'] = 'https://plus.21ds.cn/download/app/'. $param['app_id'];
    return $this->response->json(Status::CODE_OK, 'success', $returnResult);
  }
}
